"""
依赖版本验证脚本
用于快速检查所有依赖包是否正确安装且版本符合要求
"""

def check_version(package_name, min_version=None):
    """检查包版本"""
    try:
        pkg = __import__(package_name)
        # 特殊处理 watchdog，它没有 __version__ 属性
        if package_name == "watchdog":
            import pkg_resources
            version = pkg_resources.get_distribution("watchdog").version
        else:
            version = getattr(pkg, '__version__', '未知版本')
        
        status = "✅"
        msg = ""
        
        if min_version and version != '未知版本':
            # 简单的版本比较
            try:
                current_parts = list(map(int, version.split('.')[:2]))
                required_parts = list(map(int, min_version.split('.')[:2]))
                
                if current_parts < required_parts:
                    status = "⚠️ "
                    msg = f" (需要 >= {min_version})"
            except ValueError:
                # 版本号格式不标准时的处理
                status = "⚠️ "
                msg = f" (版本格式异常)"
        
        print(f"{status} {package_name:15} {version}{msg}")
        return status == "✅"
        
    except ImportError:
        print(f"❌ {package_name:15} 未安装")
        return False
    except Exception as e:
        print(f"⚠️  {package_name:15} 版本检查失败: {e}")
        return False


def main():
    print("=" * 60)
    print("告警分析系统 - 依赖版本检查")
    print("=" * 60)
    print()
    
    # 核心依赖检查
    print("📦 核心框架:")
    checks_core = [
        ("fastapi", None),
        ("uvicorn", None),
        ("pydantic", None),
    ]
    
    core_ok = all(check_version(pkg, ver) for pkg, ver in checks_core)
    print()
    
    # 数据处理依赖
    print("📊 数据处理:")
    checks_data = [
        ("pandas", "2.0.0"),
        ("numpy", "1.22.4"),
        ("openpyxl", "3.1.0"),  # 重要：pandas 2.x 必需
        ("xlrd", "2.0.0"),
    ]
    
    data_ok = all(check_version(pkg, ver) for pkg, ver in checks_data)
    print()
    
    # 可视化依赖
    print("📈 数据可视化:")
    checks_viz = [
        ("matplotlib", "3.4.0"),
        ("seaborn", "0.11.0"),
    ]
    
    viz_ok = all(check_version(pkg, ver) for pkg, ver in checks_viz)
    print()
    
    # 其他依赖
    print("🔧 其他工具:")
    checks_others = [
        ("watchdog", "2.1.0"),
        ("requests", "2.26.0"),
    ]
    
    others_ok = all(check_version(pkg, ver) for pkg, ver in checks_others)
    print()
    
    # 总结
    print("=" * 60)
    all_ok = core_ok and data_ok and viz_ok and others_ok
    
    if all_ok:
        print("✅ 所有依赖检查通过！系统可以正常运行。")
    else:
        print("❌ 部分依赖需要更新或安装")
        print()
        print("修复建议:")
        print("  1. 运行: pip install -r requirements.txt")
        print("  2. 如果仍有问题，运行: pip install --upgrade -r requirements.txt")
        print("  3. 特别注意: openpyxl 必须 >= 3.1.0 (pandas 2.x 要求)")
    
    print("=" * 60)
    print()
    
    # 额外的兼容性检查
    try:
        import pandas as pd
        import openpyxl
        
        print("🔍 关键兼容性检查:")
        
        # 检查 pandas 和 openpyxl 版本兼容性
        pandas_ver = tuple(map(int, pd.__version__.split('.')[:2]))
        openpyxl_ver = tuple(map(int, openpyxl.__version__.split('.')[:2]))
        
        if pandas_ver >= (2, 0) and openpyxl_ver < (3, 1):
            print("❌ 警告: pandas 2.x 需要 openpyxl >= 3.1.0")
            print(f"   当前 pandas {pd.__version__} 与 openpyxl {openpyxl.__version__} 不兼容")
            print("   请运行: pip install --upgrade openpyxl")
        else:
            print("✅ pandas 和 openpyxl 版本兼容")
        
        # 测试 Excel 读取功能
        print()
        print("🧪 功能测试:")
        try:
            import tempfile
            import os
            test_data = pd.DataFrame({'test': [1, 2, 3]})
            # 创建临时文件进行测试
            with tempfile.NamedTemporaryFile(suffix='.xlsx', delete=False) as tmp:
                tmp_path = tmp.name
            try:
                test_data.to_excel(tmp_path, index=False, engine='openpyxl')
                # 读取测试
                pd.read_excel(tmp_path, engine='openpyxl')
                print("✅ Excel 读写功能正常")
            finally:
                # 清理临时文件
                if os.path.exists(tmp_path):
                    os.unlink(tmp_path)
        except Exception as e:
            print(f"❌ Excel 读写功能异常: {e}")
        
        # 测试可视化功能
        try:
            import matplotlib.pyplot as plt
            fig, ax = plt.subplots()
            plt.close(fig)
            print("✅ 可视化功能正常")
        except Exception as e:
            print(f"❌ 可视化功能异常: {e}")
            
    except Exception as e:
        print(f"⚠️  兼容性检查失败: {e}")
    
    print()
    return 0 if all_ok else 1


if __name__ == "__main__":
    import sys
    sys.exit(main())
